#pragma once
#include <iostream>
#include <string>
#include <memory>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "InetAddr.hpp"
#include "Log.hpp"

namespace socket_ns
{
    enum
    {
        USE_ERR,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
    };

    static const int defaultFd = -1;
    static const int gBackLog = 6;

    class Socket
    {
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindSocketOrDie(const InetAddr &addr) = 0;
        virtual void ListenSocketOrDie() = 0;
        virtual int Accepter(InetAddr &addr) = 0; 
        virtual bool Connector(const InetAddr &addr) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;
        virtual int Send(const std::string &) = 0;
        virtual int Recv(std::string &) = 0;
        virtual void SetSockAddrReUse() = 0;

        void BuildListenSocket(const InetAddr &addr)
        {
            CreateSocketOrDie();
            SetSockAddrReUse();
            BindSocketOrDie(addr);
            ListenSocketOrDie();
        }
        bool BuildClientSock(const InetAddr &addr)
        {
            CreateSocketOrDie();
            return Connector(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sock = defaultFd)
            : _listenSock(sock)
        {
        }
        void CreateSocketOrDie() override
        {
            _listenSock = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_listenSock < 0)
            {
                LOG(FATAL, "socket create error\n");
                exit(USE_ERR);
            }
            LOG(INFO, "sock create success\n");
        }
        void BindSocketOrDie(const InetAddr &addr) override
        {
            struct sockaddr_in local = addr.Addr();
            int n = ::bind(_listenSock, reinterpret_cast<struct sockaddr *>(&local), sizeof local);
            if (n < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERR);
            }
            LOG(INFO, "bind success\n");
        }
        void ListenSocketOrDie() override
        {
            int n = ::listen(_listenSock, gBackLog);
            if (n < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERR);
            }
            LOG(INFO, "listen success\n");
        }
        void SetSockAddrReUse() override
        {
            int opt = 1;
            ::setsockopt(_listenSock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof opt);
        }

        int Accepter(InetAddr &addr) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;
            int newfd = ::accept(_listenSock, reinterpret_cast<struct sockaddr *>(&peer), &len);
            if (newfd < 0)
            {
                LOG(WARNING, "accept fail\n");
                return -1;
            }
            addr = peer;
            return newfd;
        }
        bool Connector(const InetAddr &addr) override
        {
            struct sockaddr_in peer = addr.Addr();
            int n = ::connect(_listenSock, reinterpret_cast<struct sockaddr *>(&peer), sizeof peer);
            if (n < 0)
            {
                LOG(ERROR, "connect fail\n");
                return false;
            }
            return true;
        }
        int Sockfd() override
        {
            return _listenSock;
        }
        void Close() override
        {
            if (_listenSock > defaultFd) // defaultFd is -1
                ::close(_listenSock);
        }
        int Send(const std::string & message) override
        {
            ssize_t n = ::send(_listenSock, message.c_str(), message.size(), 0);
            return n;
        }
        int Recv(std::string &inbuffer) override
        {
            char buff[4096];
            ssize_t n = ::recv(_listenSock, buff, sizeof(buff) - 1, 0);
            if(n > 0)
            {
                buff[n] = 0;
               inbuffer += buff;
            }
            return n;
        }
        ~TcpSocket()
        {
            Close();
        }

    private:
        int _listenSock;
    };
}